package com.cad3d.filemanager.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.StrutsStatics;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.cad3d.filemanager.utils.*;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor implements
		StrutsStatics {

	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(LoginInterceptor.class);
	private static final String USER_HANDLE = "loggedInUser";
	private static final String LOGIN_ATTEMPT = "logginAttempt";

	public void init() {
		log.info("Initizlizing loggin Interceptor");
	}

	public void destroy() {
		log.info("Destroy loggin Interceptor");
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		final ActionContext context = invocation.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) context
				.get(HTTP_REQUEST);
		HttpSession session = request.getSession();

		Object user = session.getAttribute(USER_HANDLE);
		if (user == null) {
			String loginAttempt = request.getParameter(LOGIN_ATTEMPT);
			if (!StringUtils.isNullOrEmpty(loginAttempt)) {
				return invocation.invoke();
			}
			return "login";
		} else {
			return invocation.invoke();
		}

	}
}
